package io.file;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AIODemo {

	public static void main(String[] args) throws Exception {

		new File("D:\\testAIOFile.txt").deleteOnExit();

		ByteBuffer writeBuffer = ByteBuffer.allocate(1024 * 1024);
		writeBuffer.put("hello nio file test ~".getBytes());
		AsynchronousFileChannel writeChannel = AsynchronousFileChannel.open(Paths.get("D:\\testAIOFile.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
		writeBuffer.flip();
		// 两种写法：回调函数或者Future都可以
		// Future<Integer> writeFuture = channel.write(writeBuffer, writeBuffer.position());
		writeChannel.write(writeBuffer, writeBuffer.position(), writeBuffer, new MyCompletionHandler());
		writeChannel.close();


		ByteBuffer readBuffer = ByteBuffer.allocate(1024 * 1024);
		AsynchronousFileChannel readChannel = AsynchronousFileChannel.open(Paths.get("D:\\testAIOFile.txt"), StandardOpenOption.READ);
		// 两种写法：回调函数或者Future都可以
		// Future<Integer> read = readChannel.read(readBuffer, 0);
		// read.get();
		// System.out.println(new String(readBuffer.array()));
		readChannel.read(readBuffer, 0, readBuffer, new MyCompletionHandler());

		readChannel.close();
	}
}

class MyCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		System.out.println(result);
		System.out.println(new String(attachment.array()));
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		exc.printStackTrace();
		System.out.println(new String(attachment.array()));
	}
}